﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.UserInfoCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Response.User;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.UserInfoHandler
{
    public class UserFindIdCommandHandlers : IRequestHandler<UserFindIdCommand, ApiResult<UserFindIdDto>>
    {
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly ILogger<UserFindIdCommandHandlers> _logger;
        private readonly IMapper _mapper;

        public UserFindIdCommandHandlers(IMapper mapper, IUserInfoRepository userInfoRepository, ILogger<UserFindIdCommandHandlers> logger)
        {
            _mapper = mapper;
            _userInfoRepository = userInfoRepository;
            _logger = logger;
        }

        public async Task<ApiResult<UserFindIdDto>> Handle(UserFindIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _userInfoRepository.GetAllAsunc(x=>x.id==request.id&&x.sys_id==request.sys_id&&x.del_flag==0);
                if (user.Count == 0)
                {
                    return new ApiResult<UserFindIdDto>() { Code = ResultCode.NotFound, Message = "用户不存在" };
                }
                var userDto = _mapper.Map<UserFindIdDto>(user[0]);
                return new ApiResult<UserFindIdDto> { Data = userDto };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户信息失败");
                return new ApiResult<UserFindIdDto>(ResultCode.Fail, "查询用户信息失败");
            }
        }
    }
}
